#include "client.h"

/* linux network */
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

#include <QDebug>

Client::Client(QObject *parent)
    : QObject{parent}
{

}

void Client::connectToServer()
{
    int err;
    m_clientFd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    struct in_addr localIp;
    inet_aton("127.0.0.1", &localIp);
    server_addr.sin_addr.s_addr = localIp.s_addr;
    err = ::connect(m_clientFd, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if (err == -1)
    {
        emit connectStatus(0);
        return;
    }
    qDebug() << m_clientFd;
    emit connectStatus(m_clientFd);
//    while (1)
//    {
//        write(clientfd, buffer, strlen(buffer) + 1);
//    }
}

void Client::sendFilenameToServer(QString filename)
{
    QByteArray byteArray = filename.toUtf8();
    const char* charArray = byteArray.constData();
    ::write(m_clientFd, charArray, strlen(charArray) + 1);

    char buffer[4096] = {0};
    ::read(m_clientFd, buffer, sizeof buffer);
    QString msg = QString::fromUtf8(buffer);
    qDebug() << msg;
    if (!msg.startsWith("file size"))   // 打开文件失败
    {
        emit diliverHtmlToMain("0");
    }
    int size = 0;
    while ((size = ::read(m_clientFd, buffer, sizeof buffer - 1)) > 0)
    {

        QString msg = QString::fromUtf8(buffer, size);
        qDebug() << size;
        qDebug() << msg;
        emit diliverHtmlToMain('1' + msg);
    }
    qDebug() << "connect break: err = " << size;
}

